<?php
class IndexController extends Vnf_Controller_Action {
    protected $_dir;

    public function indexAction() {
    
        $this->prepareData();
    
    /*
        if ($this->view->showDefaultPage ) {
            $this->setLayout('firstpage');
            return;
        }
        
        $defaultNamespace = new Zend_Session_Namespace('Default');
        if (isset($defaultNamespace->numberOfPageRequests)) {
            // this will show content normal.
            $defaultNamespace->numberOfPageRequests;
        } else {
            // this will show default page
            // first time
            $defaultNamespace->numberOfPageRequests = true;
        }
        */
        $this->setLayout('cms');

        $currentPage = $this->view->currentPage;
        $template = @$currentPage['template'];

        //echo "index action";
        // print_r($currentPage);
//        echo "HHHHHHHHH--------";
        if ('' !=  $template && null != $template)
            $this->_helper->viewRenderer->renderScript($template);
            //exec()
//            $this->_helper->viewRenderer->renderScript('cms/list.phtml');
          //  return;
    }

    public function centerAction() {
        echo "<hr>This content output from centerAction";
        $this->_helper->viewRenderer->setViewScriptPathSpec('cms/detail.phtml');
    }
    public function headerAction() {
//        echo "kkk";
        $category = new Category();

//        echo $this->_helper->viewRenderer->getViewScriptPathSpec();die;
//        echo $this->_helper->viewRenderer->getViewScript();die;
//        die;
//        $this->_helper->viewRenderer->setViewScriptPathSpec(':controller/:action.:suffix');
//        echo $this->_helper->viewRenderer->getViewScriptPathSpec();die;
//        $root = $category->getRoot();
//        $data = $category->getTreeOfNode($root->category_id);
        $this->view->menu = $category->getMainMenu();

//        print_r($category->getMainMenu());

//        echo count($data);
        //print_r($data);
//        return;
    }

    public function footerAction() {
//        $category = new Category();

//        $root = $category->getRoot();
//        $data = $category->getTreeOfNode($root->category_id);
//        $data = $category->getCacheOfCategory();

//        print_r($category->getMainMenu());

//        echo count($data);
//        print_r($data);
//        return;
    }

    public function leftAction() {
        // set another template
        // $this->_helper->viewRenderer->setScriptAction('test');
        // :controller/:action.:suffix

        // render to another content
        //$this->_helper->viewRenderer->setViewScriptPathSpec('cms/detail.phtml');


        $currentChild = $this->view->currentChild;

        if (count($currentChild) > 0)
            $this->view->leftMenuID = $this->view->currentPageID;
        else {
            $currentPage = $this->view->currentPage;
//            print_r($currentPage);
            $this->view->leftMenuID = $currentPage['parent'];
        }
    }

    public function rightAction() {
    }

    public function blockcmsAction() {
        @$this->view->blockParams = $params = $this->_getAllParams();
        @$this->view->module = $params['module'];
        @$this->view->controller = $params['controller'];
        @$this->view->action = $params['action'];
        @$this->view->name = $name = $params['id'];
        @$this->view->showContent = $showContent = $params['showContent'];
        @$this->view->content = $showContent = $params['content'];
        @$this->view->title = $showContent = $params['title'];

        //
        $isBlockNameAldreadyExists = false;
        // get all block has been register

        $manageBlockCms = Vnf::getBlockCms();

        // check id of block has exists in this page
        if (!array_key_exists($name, $manageBlockCms)) {
            $manageBlockCms[$name] = array('id' => $name);
            Zend_Registry::set('blockcms', $manageBlockCms);
        } else {
            $isBlockNameAldreadyExists = true;
            echo "<br>$name already exists<br>";
        }
        $this->view->isBlockNameAldreadyExists = $isBlockNameAldreadyExists;
    }

    public function endcmsAction() {
        Zend_Registry::set('blockcms', array());
    }

    public function translateAction() {
        $translate = new Zend_Translate('tmx', PATH_LANG_MODULE . 'items/english.tmx', 'en');
//        echo $translate->
    }

    public function listThumbnailsAction() {
		$this->listAction();
        
        $objItem = new Item();
        $this->view->randomItems = $objItem->getRecords(null, "rand()", 10);
	}
    
    public function productcontentAction() {
        $this->view->cid = $cid = $this->_request->getParam('cid', 0);
    }
    
    public function listAction() {
    
        $this->processLoginAction();
        
    
        // get category id
        $catID = $this->_request->getParam('cid', 0);
        $this->view->template = $template = $this->_request->getParam('template');
        $currentPage = $this->view->currentPageID;

        // get child page
        $pageWithSubPage = $this->view->currentChild;
        // join current page
        $pageWithSubPage[] = $currentPage;//['category_id'];
        // parse to string
        $strPageWithSubPage = implode(',', $pageWithSubPage);

        if ($catID > 0) {
            $where = "category_id in ($strPageWithSubPage)";
            
            $showall = $this->_request->getParam('all', 0);
            if ($showall) {
                $where = null;
            }

            $objItem = new Item();

            $totalRecords = $objItem->getTotalRecords("$where");

            $currentPaging = (int) $this->_request->getParam('page', 1);
            $currentPaging--;
            $numberPageView = 5;
            $recordsPerPage = (int) $this->_request->getParam('records', 9);
            $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:9;
            $totalPages = ceil($totalRecords/$recordsPerPage);
            $this->view->pages = $totalPages;

//            echo $currentPage;
            $link =  BASE_PATH . '/' . CURR_APP . "?pid=$currentPage&all=$showall";
            $tagID = "showbycat";
            $startRecord = $recordsPerPage * $currentPaging;
//            $order = 'CommentID DESC';
            $class = "paging";

            $paging = new Paging();
            $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, $link, $numberPageView, $tagID, $class,'false');

            $pk = $objItem->getPrimaryKey();
            $items = $objItem->getRecords($where, "$pk DESC", $recordsPerPage, $recordsPerPage * $currentPaging);

            //print_r($items);
            // get all items in current page and sub page
//            $items = $objItem->getRecords("$where", "item_id DESC");

            $this->view->allItems = $items;
        }
    }

    public function detailAction() {
        $this->setLayout('cms');
        $this->prepareData();

        $this->view->id = $this->_request->getParam('id', 0);
    }

    public function detailContentAction() {
        // get category id
        $itemID = $this->_request->getParam('id', 0);

        if ($itemID > 0) {
            $objItem = new Item();
            $item = $objItem->fetchRow("item_id = '$itemID'");

            if ($item) {
                $this->view->item = $item;
                $this->view->currentPageID = $item->category_id;
                $this->prepareData();
            }
        }

        //print_r($_SERVER);

        $currentPage = $this->view->currentPage;

        if ($currentPage['template']) {
            $detail = explode('/', $currentPage['template']);
            if (isset($detail[1])) {
                $currModule = $this->_request->getModuleName();
                $modulesPath = SRC_PATH . '/' . CURR_APP_PATH . '/modules/' . $currModule.'/views/scripts/';
                $subTemplate = $detail[0] . '/detail-page-' . $detail[1];
                if (is_file($modulesPath . $subTemplate)) {
                    $this->_helper->viewRenderer->renderScript($subTemplate);
                } else {
                    // do nothing
                    // show by default detail page
                }
            }
        }
    }

    public function lastestnewsAction() {
            $objItem = new Item();

            $pk = $objItem->getPrimaryKey();
            $items = $objItem->getRecords(null, "$pk DESC", 10);

            // get all items in current page and sub page
//            $items = $objItem->getRecords("$where", "item_id DESC");

            $this->view->lastestItems = $items;

    }

    public function prepareData() {
        $params = $this->_request->getParams();
        //$currentPageID = 0;
        $category = new Category();
        /*
        $this->view->allFullFriendlyUrl = $allFullFriendlyUrl = $category->getAllFullFriendlyUrl();

        //echo "-----" . stristr($_SERVER['REDIRECT_URL'], BASE_URL);
        if(stristr($_SERVER['REDIRECT_URL'], BASE_URL)) {
            $friendlyUrl = substr($_SERVER['REDIRECT_URL'], strlen(BASE_URL));
            $allFullFriendlyUrl = $this->view->allFullFriendlyUrl;

            //print_r($allFullFriendlyUrl);
            if (isset($allFullFriendlyUrl[$friendlyUrl])) {
                $currentPageID = $allFullFriendlyUrl[$friendlyUrl];
                $this->view->currentPageID = $currentPageID;
            }
        }

        */
        $currentPageID = $this->getParam('pid', $this->view->currentPageID);
        $id = $this->getParam('id', 0); // item id

        // get default content if has not page transfer
        $showDefaultPage = false;
        $getSubPage = false;
        if ($currentPageID <= 0) {
            $root = $category->getRoot();
            $currentPageID = $root->category_id;
            if ($id == 0) $getSubPage = true; // item id
            
            $this->view->showDefaultPage = $showDefaultPage = true;
        }
        $this->view->currentPageID =  $currentPageID;


        $allCategory = $category->getCacheOfCategory();

        $this->view->allCategory = $allCategory;

        $currentPage = $allCategory[$currentPageID];
        $categoryPath = $currentPage['all_parent']!=""?$currentPage['all_parent'].",".$currentPageID : $currentPageID;

        $this->view->categoryPath = explode(',', $categoryPath);
        $this->view->currentPage = $currentPage;

//        print_r($currentPage);

        $childPage = array();
        @$childPage = $currentPage['children'];
        $this->view->currentChild = $childPage;

        if ($getSubPage) {
            if (isset($childPage[0])) {
                $this->view->currentPageID =  $currentPageID = $childPage[0];
                $this->view->currentPage = $allCategory[$currentPageID];
            }
        }
        
        $paramsTransfer = $params;
        unset($paramsTransfer['loginform']);
        if (isset($paramsTransfer['lastparams'])) {
            $this->view->paramsEncode = $paramsTransfer['lastparams'];
            unset($paramsTransfer['lastparams']);
        } else {
            $this->view->paramsEncode = Zend_Json::encode($paramsTransfer);
        }
        
        
    }

    public function mediaAction() {
        $this->setLayout('cms');
        $this->prepareData();

        $this->view->id = $this->_request->getParam('id', 0);
    }

    public function mediacontentAction() {
        $itemID = $this->_request->getParam('id', 0);
        if ($itemID > 0) {
            $objItem = new Item();
            $item = $objItem->fetchRow("item_id = '$itemID'");

            if ($item) {
                $this->view->item = $item;
                $this->view->currentPageID = $item->category_id;
                $this->prepareData();
            }
        }
    }

    public function contentAction() {

    }

    public function contentloginAction() {
        $this->processLoginAction();
    }

    public function processLoginAction() {
        $defaultNamespace = new Zend_Session_Namespace('Default');
        
        if (!isset($defaultNamespace->access) || !$defaultNamespace->access) {
            $loginForm = $this->getParam('loginform', 0);
            
            if ($loginForm) {
                $params = $this->_request->getParams();
                
                $user = @$params['user'];
                $pwd = @$params['password'];
                
                if ($user == 'ndtco' && $pwd == 'ndtco') {
                    $defaultNamespace->access = true;
                    $this->view->access = $defaultNamespace->access;
                } else {
                    $defaultNamespace->access = false;
                    $this->view->access = $defaultNamespace->access;
                }
            }
        } else {
            $this->view->access = $defaultNamespace->access;
        }
    }
    
    public function randomitemAction() {
        $objItem = new Item();
        $this->view->randomItems = $objItem->getRecords(null, "rand()", 10);
    }
    public function ctdtAction() {
    	$objKH= new Khoahoc();
    	$objLH= new Lichhoc();
    	$khArr=array();$i=0;
    //	$this->view->khoahocArr = $objKH->getkhoahoc();
    	foreach($objKH->getkhoahoc() as $row){
    		$khArr[$i]=$row;
    		$khArr[$i]['lichhoc']=$objLH->getByKH($row['khoahoc_id']);
    		$i++;
    	}
    	/*echo '<pre>';
    	print_r($khArr);
    	echo '</pre>';die;*/
    	$this->view->khArr = $khArr;
    //	print_r(date('d/m/Y'));die;
    //	echo date_format(date('d/m/Yh:m:s'),'%w');die;
    }
	public function qchoithaoAction() {
    	$objKH= new Khoahoc();
    	$objLH= new Lichhoc();
    	$objCM= new Comment();
    	$params=$this->_request->getParams();
    //	$this->view->khoahocArr = $objKH->getkhoahoc();
    	$khArr=$objKH->getById($params['id']);
    	$khCurrent=$khArr[0];
    	$khCurrent['lichhoc']=$objLH->getByKH($khCurrent['khoahoc_id']);

		$otherArr=array();$i=0;
    //	$this->view->khoahocArr = $objKH->getkhoahoc();
    	foreach($objKH->getOther($khCurrent['khoahoc_id']) as $row){
    		$otherArr[$i]=$row;
    		$otherArr[$i]['lichhoc']=$objLH->getByKH($row['khoahoc_id']);
    		$i++;
    	}
		
    	$this->view->commentList=$objCM->getByKH($khCurrent['khoahoc_id']);
    	$this->view->otherArr = $otherArr;
    	$this->view->khCurrent = $khCurrent;
    	
    //	print_r(date('d/m/Y'));die;
    //	echo date_format(date('d/m/Yh:m:s'),'%w');die;
    }
    public function commentAction(){

    	$objCM= new Comment();
    	$params=$this->_request->getParams();
    	if(isset($params['comment_name'])&&$params['comment_job']&&isset($params['comment_email'])&&isset($params['comment_content'])&&isset($params['comment_khoahoc_id'])){
    		$data= array(	'comment_name'=>$params['comment_name'],
    					'comment_job'=>$params['comment_job'],
    					'comment_email'=>$params['comment_email'],
    					'comment_content'=>$params['comment_content'],
    					'comment_khoahoc_id'=>$params['comment_khoahoc_id']);
	    	$objCM->insert($data);
    	}
    	$this->_redirect($params['url']);
    }
    public function dangkiAction(){
    	$objLH= new Lichhoc();
    	$objDK= new Dangki();
    	$params=$this->_request->getParams();
    	//settype($id,$params['lichhoc']);
    	$result='Dang ki khong thanh cong';
    	if(isset($params['lichhoc'])&&isset($params['name'])&&isset($params['email'])&&isset($params['phone'])){
    		$id=$params['lichhoc'];
    		$data= array(	'dangki_name'=>$params['name'],
    					'dangki_email'=>$params['email'],
    					'dangki_phone'=>$params['phone'],
    					'dangki_lichhoc_id'=>$id);
	    	$objDK->insert($data);
	    	/*$lhArr=$objLH->getById($id);
	    	$where = $objLH->getAdapter()->quoteInto('lichhoc_id = ?', $id);
	    	$array=array('lichhoc_num'=>$lhArr[0]['lichhoc_num'] + 1);*/
	    	$objLH->numIncrease($id);
	    	$result='Cam on ban da dang ki khoa hoc cua chung toi';
    	}
    	if(isset($params['type'])&&$params['type']=='page')
    		$this->_redirect($params['url']);
    	$this->view->result=$result;
    	//$objLH->numIncrease($id);
    	/*echo $result;
    	$this->_helper->viewRenderer->setNoRender();*/
    }
    public function questionsAction(){
    	
    	$objCauhoi = new Cauhoi();
    	$rsCauhoi = $objCauhoi->getAllCauhoi();
    	
    	$this->view->rsCauhoi = $rsCauhoi;
    	$objDapan = new Dapan();    	
    	if(count($rsCauhoi)){
    	foreach ($rsCauhoi as $row){
			$cauhoi_id = $row->cauhoi_id;
			$data = $objDapan->getDapanByCauhoi($cauhoi_id);
			if($data){	
				$result[$row->cauhoi_id] = $data;//set data to array
			}
			else{				
				$result[$row->cauhoi_id] = null;
			}
		}
		$this->view->result = $result;		
    	}
    	
    	//handler insert traloi of user
    	if($this->getRequest()->isPost()){
    		$params = $this->getRequest()->getParams();
    		
    		$arrCauhoiId = $params['arrCauhoiId']; 
    		$answer = array();  		
    		for($i=0;$i<=count($arrCauhoiId);$i++){
    			if(@isset($params['cauhoi_'.$arrCauhoiId[$i]])){
    				$answer[$arrCauhoiId[$i]] = $params['cauhoi_'.$arrCauhoiId[$i]];
    			}
    		}
    		if(count($answer) > 0){
    			$traloi = Zend_Json::encode($answer);    			
    			$data = array(
    				'user_id' => 2,
    				'traloi' => $traloi,
    				'ngaytraloi' => date('Y-m-d H:i:s')
    			);
    			$ojbTraloi = new Traloi();
    			try {
    				$id = $ojbTraloi->insert($data);
    				
    				$this->_redirect('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&result=success&id='.$id);
    			}
    			catch (Exception $e){
    				$this->_redirect('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&result=fail');
    			}
    		}
    		else{
    			$this->_redirect('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&result=fail');
    		}
    	}
    }

    public function resultAction(){
    	$params = $this->getRequest()->getParams();
    	$id = $params['id'];
    	
    	$pid = $params['pid'];
    	$this->view->pid = $pid;
    	$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REDIRECT_URL'];
    	
    	$this->view->url = $url;
    	
    	$ojbTraloi = new Traloi();
    	
    	$ojbDapan = new Dapan();
    	
    	$user_id = 2;
    	$traloi_id = $id;
    	$whereAll = "user_id = $user_id AND traloi_id != $traloi_id";
    	$rsResult = $ojbTraloi->getResultByUserId($whereAll);
    	$this->view->rsResult = $rsResult;    	
    	
    	//get record to show by chart
    	$whereRow = "traloi_id = $traloi_id";
    	$rResult = 	$ojbTraloi->getRowResultByWhere($whereRow);
    	$arrTraloi = Zend_Json::decode($rResult->traloi);
    	foreach ($arrTraloi as $key => $row){
			$where = "dapan_id = $row";
			$data = $ojbDapan->getDapanByWhere($where);
			$arrResult[] = $data;
		}
		$this->view->arrResult = $arrResult;    	
    }
    public function leftMenuAction(){
    	$currentChild = $this->view->currentChild;

        if (count($currentChild) > 0)
            $this->view->leftMenuID = $this->view->currentPageID;
        else {
            $currentPage = $this->view->currentPage;
//            print_r($currentPage);
            $this->view->leftMenuID = $currentPage['parent'];
        }
    }
    public function gioithieuAction(){
    	$params = $this->getRequest()->getParams();    	
    }
    public function gioithieuDetailAction(){
    	$params = $this->getRequest()->getParams();    	
    }
    public function homeAction(){
   		$objItem = new Item();
        
        //get latest news        
        $rsItem = $objItem->getRowSetByWhere();
        $this->view->rsItem = $rsItem;
    }
    public function listNewsAction() {
    
      //  $this->processLoginAction();
        
    
        // get category id
        $catID = $this->_request->getParam('cid', 0);
        //$this->view->template = $template = $this->_request->getParam('template');
        $currentPage = $this->view->currentPageID;
        // get child page
        $pageWithSubPage = $this->view->currentChild;
        // join current page
        $pageWithSubPage[] = $currentPage;//['category_id'];
        // parse to string
        $strPageWithSubPage = implode(',', $pageWithSubPage);
        if ($catID == 0) {
            $where = "category_id in ($strPageWithSubPage)";
            
            $showall = $this->_request->getParam('all', 0);
            if ($showall) {
                $where = null;
            }
        }
        else $where= "category_id = $catID";
            $objItem = new Item();

            $totalRecords = $objItem->getTotalRecords("$where");

            $currentPaging = (int) $this->_request->getParam('page', 1);
            $currentPaging--;
            $numberPageView = 5;
            $recordsPerPage = (int) $this->_request->getParam('records', 9);
            $recordsPerPage = $recordsPerPage > 0? $recordsPerPage:9;
            $totalPages = ceil($totalRecords/$recordsPerPage);
            $this->view->pages = $totalPages;

//            echo $currentPage;
            $link =  BASE_PATH . '/' . CURR_APP . "?pid=$currentPage";
            $tagID = "showbycat";
            $startRecord = $recordsPerPage * $currentPaging;
//            $order = 'CommentID DESC';
            $class = "paging";

            $paging = new Paging();
            $this->view->paging = $paging->getPaging($currentPaging + 1, $totalPages, $link, $numberPageView, $tagID, $class,'false');

            $pk = $objItem->getPrimaryKey();
            $items = $objItem->getRecords($where, "$pk DESC", $recordsPerPage, $recordsPerPage * $currentPaging);
		//	print_r($items);die;
            //print_r($items);
            // get all items in current page and sub page
//            $items = $objItem->getRecords("$where", "item_id DESC");

            $this->view->allItems = $items;
    }
    public function detailNewsAction() {
        // get category id
        $itemID = $this->_request->getParam('id', 0);

        if ($itemID > 0) {
            $objItem = new Item();
            $item = $objItem->fetchRow("item_id = '$itemID'");
            if ($item) {
                $item = $item->toArray();
                $this->view->item=$item;
                //$this->view->currentPageID = $item->category_id;
                $this->prepareData();
            }
           	$where="item_id !='$itemID' AND category_id = '".$item['category_id']."'";
           	$pk = $objItem->getPrimaryKey();
           	$this->view->allItems = $objItem->getRecords($where, "$pk DESC", 4);
        }
		
        //print_r($_SERVER); 
    }
    public function latestNewsAction() {
            $objItem = new Item();
    		$currentPage = $this->view->currentPageID;
        	$pageWithSubPage = $this->view->currentChild;
        	$pageWithSubPage[] = $currentPage;//['category_id'];
        	$strPageWithSubPage = implode(',', $pageWithSubPage);
            $where = "category_id in ($strPageWithSubPage)";
            $pk = $objItem->getPrimaryKey();
            $items = $objItem->getRecords($where, "$pk DESC", 5);

            // get all items in current page and sub page
//            $items = $objItem->getRecords("$where", "item_id DESC");

            $this->view->latestItems = $items;

    }
	public function listCatAction() {
            $objCat = new Category();
        	$subPage = $this->view->currentChild;
        	$listCat= array();
        	foreach($subPage as $row){
        		$listCat[]=$objCat->getById($row);
        	}
            // get all items in current page and sub page
//            $items = $objItem->getRecords("$where", "item_id DESC");
	
            $this->view->listCat = $listCat;

    }
    
    
}